package jbl.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import jbl.dao.LogDaoI;
import jbl.dao.TuserDaoI;
import jbl.dao.TuserGroupDaoI;
import jbl.model.Code_log;
import jbl.model.Code_tusergroup;
import jbl.model.Tuser;
import jbl.pageModel.DataGrid;
import jbl.pageModel.User;
import jbl.service.UserServiceI;
import jbl.util.Encrypt;
import jbl.util.IpUtil;
import jbl.util.Json;
import jbl.util.Message;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("userService")
public class TuserServiceImpl implements UserServiceI {
	
	
	private TuserDaoI tuserDao;
	private TuserGroupDaoI tuserGroupDao;
	private LogDaoI logDao;
	
	@Autowired
	public void setLogDao(LogDaoI logDao) {
		this.logDao = logDao;
	}
	
	
	public TuserGroupDaoI getTuserGroupDao() {
		return tuserGroupDao;
	}
	@Autowired
	public void setTuserGroupDao(TuserGroupDaoI tuserGroupDao) {
		this.tuserGroupDao = tuserGroupDao;
	}
	public TuserDaoI getTuserDao() {
		return tuserDao;
	}
	@Autowired
	public void setTuserDao(TuserDaoI tuserDao) {
		this.tuserDao = tuserDao;
	}

	/**
	 * 查询登录
	 */
	@Override
	public Json checkLogin(User user) {
		// TODO Auto-generated method stub
		Json j = new Json();
		HttpSession session = ServletActionContext.getRequest().getSession();
		String randomCode = (String) session.getAttribute("randomCode");
		Code_log log = null;
		String ip = IpUtil.getIpAddr(ServletActionContext.getRequest());
		
		/*if(!randomCode.equals(user.getVerifyCode().trim())){
			j.setMsg("对不起，您的验证码输入错误");
			log = new Code_log(Encrypt.createUUID(), user.getUser(), ip, j.getMsg(), Timestamp.valueOf(Message.timeFormat.format(new Date())));
			logDao.save(log);
			return j;
		}*/
			String hql="from Tuser where user=? and password=?";
			Tuser tuser = tuserDao.get(hql, new Object[]{user.getUser(),Encrypt.md5(user.getPassword())});
			
			if(tuser!=null){
				session.setAttribute("user", tuser);
				
				User tp=new User();
				BeanUtils.copyProperties(tuser, tp);
				pkList(tuser, tp);
				
				tp.setIp(ip);
				j.setSuccess(true);
				j.setMsg("登录成功！");
				j.setObj(tp);
			}else{
				j.setMsg("用户名或密码错误，请重新输入！");
			}
		log = new Code_log(Encrypt.createUUID(), user.getUser(), ip, j.getMsg(), Timestamp.valueOf(Message.timeFormat.format(new Date())));
		logDao.save(log);
		return j;
	}

	//获得用户dataGrid
	@Override
	public DataGrid getDataGrid(User user) {
		DataGrid j=new DataGrid();
		String hql="from Tuser t where 1=1";
		
		Map<String,Object> values=new HashMap<String,Object>();
		List<Tuser> list=null;	
		hql = addWhere(hql ,user, values);
		String totalHql = "select count(*) "+hql;
		hql = addOrder(hql , user);
		list=tuserDao.find(hql, values,user.getPage(), user.getRows());

		List<User> lt=new ArrayList<User>();
		for(Tuser l:list){
			User tp=new User();
			BeanUtils.copyProperties(l, tp);
			pkList(l,tp);
			lt.add(tp);
		}
		j.setRows(lt);
		j.setTotal(tuserDao.count(totalHql, values));
		return j;
	}
	
	private void pkList(Tuser l , User user){
		Code_tusergroup tuserGroup = l.getTuserGroup();
		if(null != tuserGroup){
			List<Object> list = new ArrayList<Object>();
			list.add(tuserGroup.getUserGroupName());
			list.add(tuserGroup.getId());
			user.setUserGroupList(list);
		}
	}
	
	private String addOrder(String hql , User user){
		if(null != user.getSort()){
			if("userGroupList".equals(user.getSort())){
				user.setSort("tuserGroup.id");
			}
			hql += " order by t."+user.getSort() +" " + user.getOrder();
		}
		return hql;
	}
	
	public String addWhere(String hql,User user,Map<String,Object> values){
		if(user.getUser()!=null && !user.getUser().trim().equals("")){
			hql+=" and t.user like '%%"+user.getUser().trim()+"%%'";
		}

		if(user.getStartCjsj()!=null&&!user.getStartCjsj().equals("")){
			hql+=" and t.cjsj>=:start";
			values.put("start",user.getStartCjsj());
		}
		if(user.getEndCjsj()!=null&&!user.getEndCjsj().equals("")){
			hql+=" and t.cjsj<=:end";
			values.put("end",user.getEndCjsj());
		}
		return hql;
	}
	
	//添加用户
	public void addUser(User user) {
			Tuser tuser=new Tuser();
			BeanUtils.copyProperties(user, tuser);
			Code_tusergroup tusergroup = new Code_tusergroup();
			if(null != user.getUserGroupList()){
				tusergroup.setId(user.getUserGroupList().get(0).toString());
				tuser.setTuserGroup(tusergroup);
			}

			tuser.setPassword(Encrypt.md5(Message.MOREN_PASSWORD));
			tuser.setId(Encrypt.createUUID());
			tuserDao.save(tuser);
		
	}

	//修改用户
	public void update(User user) {
		Tuser tuser=new Tuser();
		BeanUtils.copyProperties(user, tuser);
		Code_tusergroup tusergroup = new Code_tusergroup();
		if(null != user.getUserGroupList()){
			tusergroup.setId(user.getUserGroupList().get(0).toString());
			tuser.setTuserGroup(tusergroup);
		}
		tuser.setPassword(Encrypt.md5(Message.MOREN_PASSWORD));
		tuserDao.update(tuser);
	}
	
	public Json edit(User user){
		Json j = new Json();
		try {
			
			Tuser tuser=tuserDao.get(Tuser.class, user.getId());
			
			if(null == tuser){
				j.setMsg("修改用户"+user.getUser()+"失败,查询用户失败!");
				return j;
			}
			String oldPassword = Encrypt.md5(user.getOldPassword().trim());
			if(!oldPassword.equals(tuser.getPassword())){
				j.setMsg("修改用户"+user.getUser()+"失败,原密码不正常!");
				return j;
			}
			tuser.setName(user.getName());
			tuser.setUserDescription(user.getUserDescription());
			tuser.setPassword(Encrypt.md5(user.getPassword().trim()));
			tuserDao.update(tuser);
			j.setMsg("修改用户"+user.getUser()+"成功!");
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			j.setMsg("修改用户"+user.getUser()+"失败!");
		}
		return j;
	}
	
	//删除一个用户
	public void delete(User User) {
		String ids = User.getIds();
		String[] id = ids.split(",");
		for(String i : id){
			Tuser tuser = tuserDao.get(Tuser.class, i);
			tuserDao.delete(tuser);
		}
	}

	
	@Override
	public List<User> comboboxInfo() {
		String hql="from Tuser t ";
		List<Tuser> list = new ArrayList<Tuser>();
	
		list=tuserDao.find(hql);
		List<User> lt=new ArrayList<User>();
		for(Tuser l:list){
			User tp=new User();
			BeanUtils.copyProperties(l, tp);
			pkList(l, tp);
			lt.add(tp);
		}
			return lt;
	}
	
	
}
